<template>
  <!-- 后期需要优化的地方，在对于无需的章节构建成一个有序的属性结构的过程中，前端的计算过于多了，使用的变量也比较多 -->
  <!-- 可以考虑一下使用设计模式 或者computed,以及一些select初始化问题 -->
  <div class="chapter">
    <div class="chapter-head">
      <h2 class="f1">目录</h2>
      <el-button type="primary" @click="openDelete" v-if="role == 'teacher'"
        >删除章节</el-button
      >
      <el-button type="primary" @click="openDia" v-if="role == 'teacher'"
        >新增章节</el-button
      >
      <p>
        <a class="f-fcgreen" target="_blank">查看帮助</a>
      </p>
    </div>
    <div v-for="(item, index) in chapterList" :key="index">
      <my-collapse
        :chapter="item"
        @deleteOne="deleteOneCh"
        @reName="reName"
      ></my-collapse>
    </div>
  </div>
  <el-dialog
    v-model="dialogVisible"
    title="新增"
    width="40%"
    center
    @close="closeDia"
  >
    <div style="margin-top: 20px">
      <el-radio-group v-model="radio" @change="test()">
        <el-radio label="1" border>新增章节</el-radio>
        <el-radio label="2" border>新增小节</el-radio>
      </el-radio-group>
    </div>
    <!-- 新增以及章节 -->
    <div v-show="this.radio == 1">
      <el-form class="one" ref="form" :rules="rules">
        <el-form-item label="章节" prop="first">
          <el-select v-model="value" placeholder="选择章节">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="second">
          <el-input
            class="title-input"
            v-model="input"
            placeholder="章节名称"
            clearable
          />
        </el-form-item>
      </el-form>
    </div>
    <!-- 新增二级章节 -->
    <div v-show="this.radio == 2">
      <el-form class="two" ref="form" :rules="rules">
        <el-form-item label="章节" prop="first">
          <el-select v-model="fatherValue" placeholder="选择章节">
            <el-option
              v-for="item in father"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="小节" prop="second">
          <el-input
            class="title-input"
            v-model="childInput"
            placeholder="小节名称"
            clearable
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addChapter">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog
    v-model="dialogVisible1"
    title="删除"
    width="40%"
    center
    @close="closeDelet"
  >
    <el-form class="one" ref="form" :rules="rules">
      <el-form-item label="章节" prop="first">
        <el-select v-model="deleteValue1" placeholder="选择章节">
          <el-option
            v-for="(item, index) in chapterList"
            :key="index"
            :label="item.title"
            :value="item.chapterId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="小节" prop="second">
        <el-select v-model="deleteValue2" placeholder="选择章节">
          <el-option
            v-for="(item, index) in session"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取消</el-button>
        <el-button type="primary" @click="deletaChapter">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { reactive, ref } from "vue";

import MyCollapse from "@/components/myComponent/myCollapse.vue";
import { useRoute } from "vue-router";
import { getChapters, addChapter, deleteBatch, seeionEdit } from "@/api/course";
import { ElMessage } from "element-plus";
import { mapGetters } from "vuex";
export default {
  components: {
    MyCollapse,
  },
  setup() {
    const dialogVisible = ref(false);
    // 选中值
    const radio = ref("1");
    const value = ref("");
    const fatherValue = ref("");
    const deleteValue1 = ref("");
    const deleteValue2 = ref("");
    const input = ref("");
    const childInput = ref("");
    const options = reactive([
      {
        value: "1",
        label: "第一章",
        disabled: false,
      },
      {
        value: "2",
        label: "第二章",
        disabled: false,
      },
      {
        value: "3",
        label: "第三章",
        disabled: false,
      },
      {
        value: "4",
        label: "第四章",
        disabled: false,
      },
      {
        value: "5",
        label: "第五章",
        disabled: false,
      },
      {
        value: "6",
        label: "第六章",
        disabled: false,
      },
      {
        value: "7",
        label: "第七章",
        disabled: false,
      },
      {
        value: "8",
        label: "第八章",
        disabled: false,
      },
      {
        value: "9",
        label: "第九章",
        disabled: false,
      },
      {
        value: "10",
        label: "第十章",
        disabled: false,
      },
      {
        value: "11",
        label: "第十一章",
        disabled: false,
      },
      {
        value: "12",
        label: "第十二章",
        disabled: false,
      },
      {
        value: "13",
        label: "第十三章",
        disabled: false,
      },
      {
        value: "14",
        label: "第十四章",
        disabled: false,
      },
      {
        value: "15",
        label: "第十五章",
        disabled: false,
      },
      {
        value: "16",
        label: "第十六章",
        disabled: false,
      },
      {
        value: "17",
        label: "第十七章",
        disabled: false,
      },
      {
        value: "18",
        label: "第十八章",
        disabled: false,
      },
      {
        value: "19",
        label: "第十九章",
        disabled: false,
      },
      {
        value: "20",
        label: "第二十章",
        disabled: false,
      },
    ]);
    const father = reactive([]);
    const dialogVisible1 = ref(false);
    const openDia = () => {
      dialogVisible.value = true;
    };
    const openDelete = () => {
      dialogVisible1.value = true;
    };
    const confirmEvent = () => {
      dialogVisible.value = !dialogVisible.value;
    };
    const cancelEvent = () => {
      dialogVisible.value = false;
    };
    const changeDisabled = () => {
      options[value - 1][disabled] = true;
    };
    return {
      dialogVisible,
      radio,
      value,
      deleteValue1,
      deleteValue2,
      options,
      input,
      childInput,
      fatherValue,
      father,
      dialogVisible1,
      openDelete,
      openDia,
      confirmEvent,
      cancelEvent,
      changeDisabled,
    };
  },
  // 数据源
  data() {
    return {
      visable: false,
      originList: [],
      chapterList: [],
      session: [],
      courseId: "",
      chapter: {
        courseId: "",
      },
      // 一级章节新增
      newOneChapter: {
        chapterId: "",
        context: {},
        courseId: "",
        sectionId: "0",
        title: "",
      },
      // 二级章节新增
      newTwoChapter: {
        chapterId: "",
        context: {},
        courseId: "",
        sectionId: "",
        title: "",
      },
      rules: {
        first: [{ required: true, message: "请输入", trigger: "blur" }],
        second: [{ required: false, message: "请输入", trigger: "blur" }],
      },
    };
  },

  created() {
    //将捕获到的参数进行首次保存（课程ID）
    this.courseId = this.getParams();
    this.getChapterList();
  },
  //生命周期函数---
  mounted() {},
  watch: {
    deleteValue1(newItem) {
      this.changeSession(newItem);
    },
  },
  //基本方法
  methods: {
    compare(key) {
      return function (value1, value2) {
        let a = Number(value1[key]);
        let b = Number(value2[key]);
        if (a > b) {
          return 1;
        } else if (a < b) {
          return -1;
        } else {
          return 0;
        }
      };
    },
    getParams() {
      const route = useRoute();
      let courseId = route.query.courseId;
      this.chapter.courseId = courseId;
      return courseId;
    },
    getChapterList() {
      getChapters(this.chapter).then((res) => {
        if (res.code == 200) {
          this.originList = res.data;
          this.initChapterList();
          //等待排序
          this.chapterList.sort(this.compare('chapterId'));
          this.father.sort(this.compare('value'));
        } else {
          ElMessage({
            type: "error",
            message: "获取列表失败",
          });
        }
      });
    },
    initChapterList() {
      this.chapterList = this.originList.filter((item) => item.sectionId == 0);
      for (const item of this.chapterList) {
        item.child = this.backChild(item.chapterId);
      }
      this.father = [];
      for (const item of this.chapterList) {
        this.father.push({ value: item.chapterId, label: item.title });
      }

      for (const item1 of this.chapterList)
        for (const item2 of this.options) {
          if (item1.chapterId == item2.value) {
            item2.disabled = true;
            break;
          }
        }
    },
    backChild(id) {
      return this.originList.filter(
        (item) => item.chapterId == id && item.sectionId != 0
      );
    },
    backChildLen(chapterId) {
      for (const item of this.chapterList)
        if (item.chapterId == chapterId) {
          return item.child.length;
        }
    },
    test() {
      console.log(this.radio);
    },
    addChapter() {
      // 模拟简单表单验证
      // 分两种情况
      if (this.radio == 1) {
        if (this.value == "" || this.input == "") {
          ElMessage({
            type: "warning",
            message: "请完成基本信息",
          });
          return;
        }
        // 组装对象
        this.newOneChapter.courseId = this.courseId;
        this.newOneChapter.chapterId = this.value;
        this.newOneChapter.title = this.input;
        addChapter(this.newOneChapter).then((res) => {
          //  console.log(res);
          if (res.code == 200) {
            this.dialogVisible = false;
            // this.changeDisabled();
            ElMessage({
              type: "success",
              message: "添加成功",
            });
            this.getChapterList();
          } else {
            ElMessage({
              type: "error",
              message: "添加失败",
            });
          }
        });
      }
      if (this.radio == 2) {
        if (this.fatherValue == "" || this.childInput == "") {
          ElMessage({
            type: "warning",
            message: "请完成基本信息",
          });
          return;
        }
        // 组装对象
        this.newTwoChapter.courseId = this.courseId;
        this.newTwoChapter.chapterId = this.fatherValue;
        this.newTwoChapter.title = this.childInput;
        // this.newTwoChapter.sectionId = 4;
        this.newTwoChapter.sectionId = this.backChildLen(this.fatherValue) + 1;
        addChapter(this.newTwoChapter).then((res) => {
          console.log(res);
          if (res.code == 200) {
            this.dialogVisible = false;
            // this.changeDisabled();
            ElMessage({
              type: "success",
              message: "添加成功",
            });
            this.getChapterList();
          } else {
            ElMessage({
              type: "error",
              message: "添加失败",
            });
          }
        });
      }
    },
    closeDia() {
      this.value = "";
      this.fatherValue = "";
      this.input = "";
      this.childInput = "";
    },
    closeDelet() {
      this.deleteValue1 = "";
      this.deleteValue2 = "";
    },
    deletaChapter() {
      if (this.deleteValue1 == "") {
        ElMessage({
          type: "warning",
          message: "请先输入",
        });
        return;
      } else {
        // 组装参数
        let deleteData = { chapterId: [], courseId: [], sectionId: [] };
        if (this.deleteValue2 == "") {
          for (const item of this.chapterList) {
            if (item.chapterId == this.deleteValue1) {
              deleteData.chapterId.push(item.chapterId);
              deleteData.courseId.push(item.courseId);
              deleteData.sectionId.push(item.sectionId);
              item.child.forEach((item1) => {
                deleteData.chapterId.push(item1.chapterId);
                deleteData.courseId.push(item1.courseId);
                deleteData.sectionId.push(item1.sectionId);
              });
            }
          }
        } else {
          deleteData.chapterId.push(this.deleteValue1);
          deleteData.courseId.push(this.courseId);
          deleteData.sectionId.push(this.deleteValue2);
        }
        deleteBatch(deleteData).then((res) => {
          if (res.code == 200) {
            this.dialogVisible1 = false;
            this.getChapterList();
            ElMessage({
              type: "success",
              message: "删除成功",
            });
          } else {
            ElMessage({
              type: "error",
              message: "删除失败",
            });
          }
        });
      }
    },
    changeSession(id) {
      this.session = [];
      for (const item of this.backChild(id)) {
        this.session.push({ value: item.sectionId, label: item.title });
      }
      // console.log(this.session)
    },
    deleteOneCh(e) {
      // 组装参数
      let deleteData = { chapterId: [], courseId: [], sectionId: [] };
      if (e.child) {
        deleteData.chapterId.push(e.chapterId);
        deleteData.courseId.push(e.courseId);
        deleteData.sectionId.push(e.sectionId);
        e.child.forEach((item1) => {
          deleteData.chapterId.push(item1.chapterId);
          deleteData.courseId.push(item1.courseId);
          deleteData.sectionId.push(item1.sectionId);
        });
      } else {
        deleteData.chapterId.push(e.chapterId);
        deleteData.courseId.push(e.courseId);
        deleteData.sectionId.push(e.sectionId);
      }
      deleteBatch(deleteData).then((res) => {
        if (res.code == 200) {
          this.dialogVisible1 = false;
          this.getChapterList();
          this.$router.go(0);
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "删除失败",
          });
        }
      });
    },
    reName(e, newName) {
      //组装参数
      let chapter = {};
      chapter.chapterId = e.chapterId;
      chapter.courseId = e.courseId;
      chapter.sectionId = e.sectionId;
      chapter.title = newName;
      seeionEdit(chapter).then((res) => {
        if (res.code == 200) {
          e.title = newName;
          ElMessage({
            type: "success",
            message: "修改成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "修改失败",
          });
        }
      });
    },
  },
  computed: {
    ...mapGetters({
      role: "getRole",
    }),
  },
};
</script>

<style   scoped>
a {
  text-decoration: none;
}
.chapter {
  margin-left: 15px;
  margin-right: 15px;
}
.chapter-head {
  overflow: hidden;
  min-height: 60px;
}
.f1 {
  float: left;
  font-size: 20px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
}
a.f-fcgreen {
  color: #00cc7e;
  float: right;
  font-size: 12px;
}
.course-collapse {
  border: 1px solid blue;
}
.one {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
}
.two {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
}
.title-input {
  width: 250px;
}
</style>